package org.kalai.unifypay.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.SessionManager;
import org.kalai.unifypay.bean.Bizcnf;
import org.kalai.unifypay.bean.Member;
import org.kalai.unifypay.bean.Transflow;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DataDao;
import org.kalai.unifypay.util.ProxyPayUtil;
import org.kalai.unifypay.wft.WFTUtil;

import com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class WFTNotify
 */
@WebServlet("/WFTNotify")
public class WFTNotify extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final Logger logger = Logger.getLogger(WFTNotify.class);

    /**
     * @see HttpServlet#HttpServlet()
     */
    public WFTNotify() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String resStr = WFTUtil.parseRequst(request);
        System.out.println("通知内容:  " + resStr);

        Map<String, String> map = null;
        String tranxSN = null;

        try {
            if(resStr != null && "".equals(resStr)) {
                map = WFTUtil.toMap(resStr.getBytes(), "utf-8");

                if(map.containsKey("sign")) {
                    if(!WFTUtil.checkParam(map, Constant.WFT_KEY)) {
                        logger.error(String.format("(威富通)验证签名不通过:[map=%s]", map));
                        throw new RuntimeException("验证签名不通过");
                    } else {
                        if ("0".equals(map.get("status")) && "0".equals(map.get("result_code"))) {
                            tranxSN = map.get("out_trade_no");
                            Transflow transflow = DataDao.getInstance().getTransflow(tranxSN);
                            if(transflow == null) {
                                throw new RuntimeException("订单查询为空");
                            }                            
                            if(transflow.getTransAmt() != Integer.parseInt(map.get("total_fee"))) {
                                throw new RuntimeException("订单金额校验不正确");
                            }

                            notifyManage(transflow, map);
                        }

                    }
                }

            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            logger.error("查询订单异常");
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error(String.format("(天付宝)异步通知异常:参数[map=%s],异常详情:%s", map, e));
            e.printStackTrace();
        } finally {
            logger.info("(天付宝)异步通知成功:" + tranxSN);
            CommonUtil.responseObject(response, "SUCCESS");
        }

    }

    public void notifyManage(Transflow transflow, Map<String, String> params) throws Exception {

        if(transflow.getStatus() == 1) {

            //查询商户信息是否存在
            Member member = DataDao.getInstance().getMember(transflow.getMemberNo());
            if(member == null) {
                throw new RuntimeException("商户信息不存在:" + transflow.getMemberNo());
            }

            //更新交易表
            Double tradeAmount = 0.0;  //交易金额
            if(params.get("pay_info") != null) {
                tradeAmount = Double.valueOf(params.get("total_fee"));
            }
            String respCode = "0".equals(params.get("pay_result")) ? "00" : params.get("pay_result");
            boolean isok = "00".equals(respCode);
            String respMsg = params.get("pay_info");
            if(params.get("pay_info") == null || "".equals(params.get("pay_info"))) {
                respMsg = "支付成功";
            }
            DataDao.getInstance().updateTransflow(transflow.getTranxSN(), "", tradeAmount.longValue(), isok ? 2 : 3, respCode, respMsg);

            /* 威富通交易成功后实时代付出去 */
            String bizcode = transflow.getBizcode();
            Bizcnf bizcnf = DataDao.getInstance().getBizcnfByCode(bizcode);
            if (isok && bizcnf.getPattern() == 0) {
                String settNo = CommonUtil.generSettNo();
                boolean rs = DataDao.getInstance().addSettlement(transflow.getTranxSN(), settNo, bizcode, member,
                        transflow.getTransAmt() - transflow.getTransFee(), 1);
                if (rs)
                    ProxyPayUtil.proxyPay(settNo, member,
                            ((Double) (transflow.getTransAmt() * 100 - transflow.getTransFee() * 100)).longValue(), bizcode, true);
            }

            // 异步通知账单系统
            CommonUtil.notifyTransFlow(transflow);
            /* 异步通知合作方 */
            String url = transflow.getNotifyUrl();
            String partnerCode = transflow.getPartnerCode();
            String secret = DataDao.getInstance().getPartnerByCode(partnerCode).getPartnerSecret();
            if (url != null && !"".equals(url))
                CommonUtil.notifyMessage(url, partnerCode, secret, transflow.getTranxSN(), transflow.getOrderNo(),
                        transflow.getTransAmt(), respCode, respMsg);

            /* websocket推送消息 */
            Map<String, Object> result = CommonUtil.createRespMap(respCode, respMsg);
            SessionManager.getInstance().broadcast(transflow.getTranxSN(), JSON.toJSONString(result));

        } else {
            throw new RuntimeException(transflow.getTranxSN() + "订单状态异常:status=" + transflow.getStatus());
        }

    }

}
